package com.cml.rpc.client;

import com.cml.rpc.publicpojo.RpcRequest;
import com.cml.rpc.publicpojo.RpcResponse;
import lombok.Data;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理疯涨request
 * @author cml
 * @create 2021/7/20 15:04
 */
@Data
public class RpcClientProxy implements InvocationHandler {

    private RpcClient rpcClient;

    public RpcClientProxy(RpcClient rpcClient) {
        this.rpcClient = rpcClient;
    }
    // 使用jdk动态代理，代理对象通用方法，会经过此方法增强，反射获取request对象
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // 通过反射获取接口信息
        String interfaceName = method.getDeclaringClass().getName();
        String methodName = method.getName();
        Class<?>[] paramTypes = method.getParameterTypes();

        RpcRequest rpcRequest = RpcRequest.builder().interfaceName(interfaceName)
                .methodName(methodName).params(args).paramTypes(paramTypes).build();
        // 发送数据
        RpcResponse rpcResponse = rpcClient.sendRequest(rpcRequest);
        return rpcResponse.getData();
    }

    /**
     * 获取代对象
     * @param clazz
     * @param <T>
     * @return
     */
    <T>T getProxy(Class<T> clazz) {
        Object proxyInstance = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
        return (T)proxyInstance;
    }
}
